package com.ddzj.scaffold.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
 * @Author:yangzibo
 * @CreateTime:2024-05-12 19:05
 * @Description:
 * @Version:1.0
 **/
public class AESUtils {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final byte[] IV = "1234567890123456".getBytes(StandardCharsets.UTF_8);

    public static String encrypt(String key, String plaintext) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String key, String ciphertext) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        String key = "mySuperSecretKey"; // 请使用至少16个字符的密钥
        String plaintext = "Hello, AES!";
        String ciphertext = encrypt(key, plaintext);
        System.out.println("Encrypted: " + ciphertext);
        String decrypted = decrypt(key, ciphertext);
        System.out.println("Decrypted: " + decrypted);
    }
}
